import { ElementPropertyConfig, PropertyEntity } from '@farris/ide-property-panel';
import { CodeEditorComponent } from '@farris/designer-devkit';
import { ContainerUsualProp } from '../../common/property/container-property-config';
import { UniformEditorDataUtil } from '@farris/designer-services';
import { IconSelectEditorComponent, ItemCollectionConverter, ItemCollectionEditorComponent } from '@farris/designer-devkit';
import { FormPropertyChangeObject } from '../../../../entity/property-change-entity';
import { EditorTypes } from '@farris/ui-datagrid-editors';
import { PageToolbarEditorComponent } from './editor/page-toolbar-editor/page-toolbar-editor.component';
import { PageToolbarConverter } from './editor/page-toolbar-editor/page-toolbar-converter';
import { EventsEditorFuncUtils } from '../../../../utils/events-editor-func';

export class HeaderProp extends ContainerUsualProp {
    getPropConfig(propertyData: any): ElementPropertyConfig[] {
        const viewModelId = this.viewModelId;
        const propertyConfig = [];


        // 基本信息属性
        const basicPropConfig = this.getBasicPropConfig(propertyData, viewModelId);
        propertyConfig.push(basicPropConfig);

        // 外观属性
        const appearancePropConfig = this.getAppearancePropConfig(propertyData, viewModelId);
        propertyConfig.push(appearancePropConfig);

        // 行为属性
        const behaviorPropConfig = this.getBehaviorPropConfig(propertyData, viewModelId);
        propertyConfig.push(behaviorPropConfig);

        // 按钮属性
        // const toolbarPropConfig = this.getToolbarPropConfig(propertyData, viewModelId);
        // propertyConfig.push(toolbarPropConfig);

        // 翻页属性
        // const pgPropConfig = this.getPaginationPropConfig(propertyData, viewModelId);
        // propertyConfig.push(pgPropConfig);

        // 视图切换属性
        const viewChangePropConfig = this.getViewChangePropConfig(propertyData, viewModelId);
        propertyConfig.push(viewChangePropConfig);

        // 自定义模板属性
        const templatePropConfig = this.getCustomTemplatePropConfig(propertyData, viewModelId);
        propertyConfig.push(templatePropConfig);

        // 事件属性---暂时没有场景启用多视图按钮，所以先屏蔽掉
        // const eventPropConfig = this.getEventPropConfig(propertyData, viewModelId);
        // propertyConfig.push(eventPropConfig);

        return propertyConfig;

    }


    private getBehaviorPropConfig(propertyData: any, viewModelId: string): ElementPropertyConfig {
        const visibleProp = this.getVisiblePropertyEntity(propertyData, viewModelId);
        return {
            categoryId: 'behavior',
            categoryName: '行为',
            properties: [visibleProp],
        };
    }

    private getAppearancePropConfig(propertyData: any, viewModelId: string): ElementPropertyConfig {
        const commonProps = this.getCommonAppearanceProperties();
        const props = commonProps;
        const self = this;
        props.push(
            {
                propertyID: 'mainTitle',
                propertyName: '主标题',
                propertyType: 'unity',
                description: '页头主标题',
                editorParams: {
                    controlName: UniformEditorDataUtil.getControlName(propertyData),
                    constType: 'enum',
                    editorOptions: {
                        types: ['custom', 'variable'],
                        variables: UniformEditorDataUtil.getVariables(viewModelId, this.domService),
                        getVariables: () => UniformEditorDataUtil.getVariables(viewModelId, this.domService),
                        newVariableType: 'String'
                    }
                }
            },
            {
                propertyID: 'subTitle',
                propertyName: '副标题',
                propertyType: 'string'
            },
            {
                propertyID: 'showIcon',
                propertyName: '是否显示图标',
                propertyType: 'boolean'
            },
            {
                propertyID: 'iconName',
                propertyName: '图标',
                propertyType: 'modal',
                editor: IconSelectEditorComponent,
                editorParams: { needIconClass: false },
                visible: propertyData.showIcon
            },
            {
                propertyID: 'iconCls',
                propertyName: '图标所属单据类别',
                propertyType: 'editableSelect',
                iterator: [
                    { key: 'f-text-orna-bill', value: '单据类' },
                    { key: 'f-text-orna-dict', value: '字典类' },
                    { key: 'f-text-orna-manage', value: '管理类' },
                    { key: 'f-text-orna-query', value: '查询报表类' },
                    { key: 'f-text-orna-param', value: '系统参数类' }
                ],
                visible: propertyData.showIcon
            }
        );
        return {
            categoryId: 'appearance',
            categoryName: '外观',
            properties: props,
            setPropertyRelates(changeObject: FormPropertyChangeObject, data, parameters) {
                if (!changeObject) {
                    return;
                }
                switch (changeObject.propertyID) {
                    case 'showIcon': {
                        const iconName = this.properties.find(p => p.propertyID === 'iconName');
                        if (iconName) {
                            iconName.visible = changeObject.propertyValue;
                        }
                        const iconCls = this.properties.find(p => p.propertyID === 'iconCls');
                        if (iconCls) {
                            iconCls.visible = changeObject.propertyValue;
                        }
                        break;
                    }
                }
            }
        };
    }

    private getPaginationPropConfig(propertyData: any, viewModelId: string): ElementPropertyConfig {
        const properties: PropertyEntity[] = [
            {
                propertyID: 'pgShow',
                propertyName: '是否显示翻页',
                propertyType: 'boolean'
            },
            {
                propertyID: 'pgPreDisabled',
                propertyName: '是否禁用向前翻页',
                propertyType: 'editableSelect',
                iterator: [{ key: true, value: 'true' }, { key: false, value: 'false' }]
            },
            {
                propertyID: 'pgNextDisabled',
                propertyName: '是否禁用向后翻页',
                propertyType: 'editableSelect',
                iterator: [{ key: true, value: 'true' }, { key: false, value: 'false' }]
            },
        ];

        properties.map(p => {
            if (p.propertyID !== 'pgShow') {
                p.visible = propertyData.pgShow;
            }
        });

        return {
            categoryId: 'pagination',
            categoryName: '翻页',
            properties,
            setPropertyRelates(changeObject: FormPropertyChangeObject, data, parameters) {
                if (!changeObject) {
                    return;
                }
                switch (changeObject.propertyID) {
                    case 'pgShow': {
                        this.properties.map(p => {
                            if (p.propertyID !== 'pgShow') {
                                p.visible = changeObject.propertyValue;
                            }
                        });
                        break;
                    }
                }
            }
        };
    }
    /**
     * 多视图切换按钮配置，限制只有当前页面有多视图时，才暴露视图切换属性。因为视图切换和多视图是配套使用的，而启用多视图的开关在列表上，这里不能单独配置切换按钮。
     * @param propertyData 属性值
     * @param viewModelId 视图模型id
     */
    private getViewChangePropConfig(propertyData: any, viewModelId: string): ElementPropertyConfig {

        const properties: PropertyEntity[] = [
            {
                propertyID: 'showViewChange',
                propertyName: '是否启用多视图按钮',
                propertyType: 'boolean'
            },
            {
                propertyID: 'viewType',
                propertyName: '视图按钮排列方式',
                propertyType: 'select',
                iterator: [{ key: 'tile', value: '平铺' }, { key: 'dropdown', value: '下拉选择' }]
            },
            {
                propertyID: 'viewDatas',
                propertyName: '视图按钮组',
                propertyType: 'modal',
                editor: ItemCollectionEditorComponent,
                editorParams: {
                    columns: [
                        { field: 'type', title: '类型', editor: { type: EditorTypes.TEXTBOX } },
                        { field: 'title', title: '名称', editor: { type: EditorTypes.TEXTBOX } },
                        { field: 'iconName', title: '图标样式', editor: { type: EditorTypes.TEXTBOX } },
                    ],
                    requiredFields: ['type', 'title', 'iconName'],
                    uniqueFields: ['type', 'title'],
                    modalTitle: '视图按钮编辑器'
                },
                converter: new ItemCollectionConverter(),
                visible: false
            },
            {
                propertyID: 'viewDefaultType',
                propertyName: '默认显示的视图类型',
                propertyType: 'select',
                iterator: this.getViewChangeDataTypes(propertyData)
            },
        ];

        properties.map(p => {
            if (p.propertyID !== 'showViewChange') {
                p.visible = propertyData.showViewChange;
            }
        });
        const self = this;
        return {
            categoryId: 'viewChange',
            categoryName: '视图切换',
            hide: !propertyData.viewDatas || !propertyData.viewDatas.length,
            properties,
            setPropertyRelates(changeObject: FormPropertyChangeObject, data, parameters) {
                if (!changeObject) {
                    return;
                }
                switch (changeObject.propertyID) {
                    case 'showViewChange': {
                        this.properties.map(p => {
                            if (p.propertyID !== 'showViewChange') {
                                p.visible = changeObject.propertyValue;
                            }
                        });
                        break;
                    }
                    case 'viewDatas': {
                        const defaultProp = this.properties.find(p => p.propertyID === 'viewDefaultType');
                        if (defaultProp) {
                            defaultProp.iterator = self.getViewChangeDataTypes(data);
                        }
                    }
                }
            }
        };
    }


    private getViewChangeDataTypes(propData: any) {

        if (!propData || !propData.viewDatas || propData.viewDatas.length === 0) {
            return [];
        }
        const iterators = [];
        propData.viewDatas.forEach(data => {
            iterators.push(
                {
                    key: data.type,
                    value: data.title
                }
            );
        });
        return iterators;
    }

    private getToolbarPropConfig(propertyData: any, viewModelId: string): ElementPropertyConfig {
        /** 展示模式：弹出类modal/独立页签类page/侧边滑出类slide 。
         * 优先取控件所属组件的展示类型，若没有配置，则取当前表单的展示类型
         */
        let showType = this.domService.module.showType;
        const comp = this.domService.getComponentByVMId(viewModelId);
        if (comp && comp.showType) {
            showType = comp.showType;
        }
        return {
            categoryId: 'toolbar',
            categoryName: '工具栏',
            properties: [
                {
                    propertyID: 'toolbarCls',
                    propertyName: '工具栏样式',
                    propertyType: 'string'
                },
                {
                    propertyID: 'toolbarDatas',
                    propertyName: '按钮组',
                    propertyType: 'modal',
                    editor: PageToolbarEditorComponent,
                    editorParams: { controlId: propertyData.id, viewModelId },
                    converter: new PageToolbarConverter(this.domService, propertyData.id, showType)
                },
                {
                    propertyID: 'toolbarBtnSize',
                    propertyName: '按钮尺寸',
                    propertyType: 'select',
                    iterator: [
                        { key: 'default', value: '标准' },
                        { key: 'lg', value: '大号' }
                    ]
                },
                {
                    propertyID: 'toolbarPopDirection',
                    propertyName: '弹出方向',
                    propertyType: 'select',
                    iterator: [
                        { key: 'default', value: '自动' },
                        { key: 'top', value: '向上' },
                        { key: 'bottom', value: '向下' }
                    ]
                }
            ]
        };
    }


    private getCustomTemplatePropConfig(propertyData: any, viewModelId: string): ElementPropertyConfig {
        return {
            categoryId: 'customTemplate',
            categoryName: '自定义模板',
            properties: [
                {
                    propertyID: 'titleTemplate',
                    propertyName: '左侧标题区域模板',
                    propertyType: 'modal',
                    editor: CodeEditorComponent,
                    editorParams: {
                        language: 'html'
                    }
                },
                {
                    propertyID: 'titleTemplateCls',
                    propertyName: '左侧标题区域模板样式',
                    propertyType: 'string'
                },
                {
                    propertyID: 'contentTemplate',
                    propertyName: '中间内容区域模板',
                    propertyType: 'modal',
                    editor: CodeEditorComponent,
                    editorParams: {
                        language: 'html'
                    }
                },
                {
                    propertyID: 'contentTemplateCls',
                    propertyName: '中间内容区域模板样式',
                    propertyType: 'string'
                },
                {
                    propertyID: 'downTemplate',
                    propertyName: '下方扩展区域模板',
                    propertyType: 'modal',
                    editor: CodeEditorComponent,
                    editorParams: {
                        language: 'html'
                    }
                },
                {
                    propertyID: 'downTemplateCls',
                    propertyName: '下方扩展区域模板样式',
                    propertyType: 'string'
                }
            ]
        };
    }

    private getEventPropConfig(propertyData: any, viewModelId: string, showPosition = 'card'): ElementPropertyConfig {
        const self = this;
        const domService = this.domService;
        const webCmdService = this.webCmdService;
        const formBasicService = this.formBasicService;
        const eventEditorService = this.eventEditorService;
        const eventList = this.switchEvents(propertyData, []);
        return {
            categoryId: 'eventsEditor',
            categoryName: '事件',
            hideTitle: true,
            properties: EventsEditorFuncUtils.formProperties(eventEditorService, formBasicService, domService, webCmdService, propertyData, viewModelId, eventList, self.switchEvents),
            tabId: 'commands',
            tabName: '交互',
            setPropertyRelates(changeObject: FormPropertyChangeObject, data, parameters) {
                delete propertyData[viewModelId];
                EventsEditorFuncUtils.saveRelatedParameters(eventEditorService, domService, webCmdService, propertyData, viewModelId, parameters['events'], parameters);
                this.properties = EventsEditorFuncUtils.formProperties(eventEditorService, formBasicService, domService, webCmdService, propertyData, viewModelId, parameters['events'], self.switchEvents);
            }
        };
    }

    private switchEvents(propertyData: any, eventList: any[]) {
        if (propertyData.showViewChange) {

            if (!eventList.find(eventListItem => eventListItem.label == 'viewTypeChange')) {
                eventList.push(
                    {
                        label: 'viewTypeChange',
                        name: '视图类型切换事件',
                    }
                )
            }
        } else {
            eventList = eventList.filter(eventListItem => {
                if (eventListItem.label != 'viewTypeChange')
                    return true;
            })
        }
        return eventList;
    }
}
